<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>接口测试</el-breadcrumb-item>
      <el-breadcrumb-item>辅助函数</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!--搜索框-->
        <el-col :span="6">
          <el-input placeholder="请输入项目名称" v-model="queryParams.project" clearable @clear="getFunctionList" @keyup.enter.native="getFunctionList">
            <el-button slot="append" icon="el-icon-search" @click="getFunctionList" class="search"></el-button>
          </el-input>
        </el-col>
        <!--创建按钮-->
        <el-col :span="4">
          <el-button type="primary" @click="openAddFunctionDialog" plain>创建辅助函数文件</el-button>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table :data="functionList" :cell-style="cellStyle" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="文件名称" prop="name"></el-table-column>
        <el-table-column label="所属项目" prop="project"></el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column label="操作" min-width="130px">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="openEditFunctionDialog(scope.row)" plain>编 辑</el-button>
            <el-button type="danger" size="mini" @click="deleteThisFunction(scope.row.id)" plain>删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.p"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="queryParams.s"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--新建辅助函数对话框-->
    <el-dialog title="创建辅助函数文件" :visible.sync="addFunctionDialogVisible" style="" width="60%" :append-to-body="true"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="addDialogClose">
      <!--辅助函数表单-->
      <el-form :model="addFunctionForm" status-icon :rules="addFunctionRule" ref="addFunctionRef" label-width="90px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="addFunctionForm.project_id" placeholder="请选择所属项目">
            <el-option
              v-for="project in projectAndInterfaceNames"
              :key="project.id"
              :label="project.name"
              :value="project.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="addFunctionForm.name" placeholder="请输入文件名称" disabled></el-input>
        </el-form-item>
        <el-form-item label="文件内容" prop="content">
          <editor ref="fileContentRef" v-model="addFunctionForm.content" @init="fileContentInit" lang="python" theme="chrome"
                  style="width: 100%; height: 320px; border: rgb(136 136 136) solid 1px" :options="{
             tabSize:2,
             fontSize:14,
             showPrintMargin:false,
             enableSnippets: true,
             enableLiveAutocompletion: true,
             enableBasicAutocompletion: true
           }"></editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addFunctionDialogClose">取 消</el-button>
          <el-button type="primary" @click="addFunction">确 定</el-button>
        </span>
    </el-dialog>
    <!--编辑辅助函数对话框-->
    <el-dialog title="编辑辅助函数文件" :visible.sync="editFunctionDialogVisible" width="60%" :append-to-body="true"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="editDialogClose">
      <!--辅助函数表单-->
      <el-form :model="editFunctionForm" status-icon :rules="editFunctionRule" ref="editFunctionRef" label-width="90px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="editFunctionForm.project_id" placeholder="请选择所属项目">
            <el-option
              v-for="project in projectAndInterfaceNames"
              :key="project.id"
              :label="project.name"
              :value="project.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="editFunctionForm.name" placeholder="请输入文件名称" disabled></el-input>
        </el-form-item>
        <el-form-item label="文件内容" prop="content">
          <editor ref="fileContentRef" v-model="editFunctionForm.content" @init="fileContentInit" lang="python" theme="chrome"
                  style="width: 100%; height: 320px; border: rgb(136 136 136) solid 1px" :options="{
             tabSize:2,
             fontSize:14,
             showPrintMargin:false,
             enableSnippets: true,
             enableLiveAutocompletion: true,
             enableBasicAutocompletion: true
           }"></editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editFunctionDialogClose">取 消</el-button>
          <el-button type="primary" @click="editThisFunction">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import { getFunctions, getProjectAndInterfaceNames, createFunction, editFunction, deleteFunction } from '../../api/api'
import Editor from 'vue2-ace-editor'

export default {
  components: {
    Editor
  },
  created () {
    this.getFunctionList()
    this.getProjectAndInterfaceNameList()
  },
  data () {
    return {
      functionList: [],
      queryParams: {
        p: 1,
        s: 10,
        project: ''
      },
      tmpName: '',
      addFunctionDialogVisible: false,
      addFunctionForm: {
        name: 'debugtalk.py',
        project_id: '',
        content: '# author: suanmiao'
      },
      projectAndInterfaceNames: {},
      editFunctionDialogVisible: false,
      editFunctionForm: {},
      total: 0,
      functionId: '',
      addFunctionRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '辅助函数文件名称不能为空！', trigger: 'blur' },
          { min: 4, max: 50, message: '长度在 4 到 50 个字符！', trigger: 'blur' }
        ]
      },
      editFunctionRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '辅助函数文件名称不能为空！', trigger: 'blur' },
          { min: 4, max: 50, message: '长度在 4 到 50 个字符！', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 辅助函数文件内容初始化
    fileContentInit () {
      require('brace/ext/language_tools')
      require('brace/mode/python')
      require('brace/snippets/python')
      require('brace/theme/chrome')
    },
    // 获取辅助函数文件列表
    getFunctionList () {
      if (this.queryParams.name !== this.tmpName) {
        this.tmpName = this.queryParams.name
        this.queryParams.p = 1
      }
      getFunctions(this.queryParams)
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取辅助函数文件列表失败！')
          this.functionList = response.data.data.results
          this.total = response.data.data.count
        })
    },
    // 获取项目名称列表
    getProjectAndInterfaceNameList () {
      getProjectAndInterfaceNames()
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取项目名称列表失败！')
          this.projectAndInterfaceNames = response.data.data
        })
    },
    // 打开创建辅助函数文件对话框
    openAddFunctionDialog () {
      this.addFunctionDialogVisible = true
    },
    // 创建辅助函数文件
    addFunction () {
      this.$refs.addFunctionRef.validate(valid => {
        if (!valid) return
        createFunction(this.addFunctionForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('创建辅助函数文件失败！')
            this.$message.success('创建辅助函数文件成功！')
            this.addFunctionDialogClose()
            this.getFunctionList()
          })
      })
    },
    // 创建对话框关闭
    addDialogClose () {
      this.$refs.addFunctionRef.resetFields()
      this.addFunctionForm = {
        name: '',
        project_id: '',
        content: '# author: suanmiao'
      }
    },
    // 创建辅助函数对话框关闭
    addFunctionDialogClose () {
      this.addFunctionDialogVisible = false
      this.addDialogClose()
    },
    // 打开编辑辅助函数文件对话框
    openEditFunctionDialog (functionInfo) {
      this.editFunctionForm = { ...functionInfo }
      this.functionId = this.editFunctionForm.id
      delete this.editFunctionForm.id
      delete this.editFunctionForm.project
      delete this.editFunctionForm.create_time
      this.editFunctionDialogVisible = true
    },
    // 编辑对话框关闭
    editDialogClose () {
      this.$refs.editFunctionRef.resetFields()
    },
    // 编辑辅助函数文件对话框关闭
    editFunctionDialogClose () {
      this.editFunctionDialogVisible = false
      this.editDialogClose()
    },
    // 编辑这个函数文件
    editThisFunction () {
      this.$refs.editFunctionRef.validate(valid => {
        if (!valid) return
        editFunction(this.functionId, this.editFunctionForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('编辑辅助函数文件失败！')
            this.$message.success('编辑辅助函数文件成功！')
            this.editFunctionDialogClose()
            this.getFunctionList()
          })
      })
    },
    // 删除这个函数文件
    deleteThisFunction (functionId) {
      this.$confirm('此操作将永久删除该辅助函数文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFunction(functionId).then(response => {
          if (response.data.code !== 0) return this.$message.error('删除辅助函数文件失败！')
          this.$message.success('删除辅助函数文件成功！')
          this.total -= 1
          if (this.total === (this.queryParams.p - 1) * this.queryParams.s && this.total !== 0) {
            this.queryParams.p -= 1
          }
          this.getFunctionList()
        })
      }).catch(err => err)
    },
    // 监听size变化
    handleSizeChange (newSize) {
      this.queryParams.s = newSize
      this.getProjectList()
    },
    // 监听页码变化
    handleCurrentChange (newPage) {
      this.queryParams.p = newPage
      this.getProjectList()
    },
    // 表格样式
    cellStyle (data) {
      if (data.column.label === '文件名称') {
        return 'color: #409EFF'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .el-dialog__body {
    height: 450px;
    padding: 20px 35px 10px 20px;
  }
</style>
